package com.dff.jrfw;

import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import androidx.databinding.DataBindingUtil;

import com.dff.jrfw.common.Constant;
import com.dff.jrfw.databinding.ActivityPsdLoginBinding;
import com.dff.jrfw.model.AuthCodeModel;
import com.dff.jrfw.model.LoginModel;
import com.dff.jrfw.model.TokenBodyModel;
import com.dff.jrfw.model.TokenUserNameModel;
import com.dff.jrfw.remote.CustomCallBack;
import com.dff.jrfw.remote.RetrofitUtils;
import com.dff.jrfw.remote.RetrofitUtilsTwo;
import com.dff.jrfw.requestBody.LoginDto;
import com.dff.jrfw.utils.CertUtils;
import com.dff.jrfw.utils.GsonUtils;
import com.dff.jrfw.utils.SharedPreferenceUtils;
import com.dff.jrfw.utils.ToastUtil;
import com.dff.jrfw.utils.Util;
import com.dff.jrfw.utils.XORUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

public class PsdLoginActivity extends BaseActivity implements View.OnClickListener {

    private ActivityPsdLoginBinding binding;
    private int psdVisible = 0;    //默认密码不可见
    private String username;

    public static void callMe(Context context, String username) {
        Intent intent = new Intent(context, PsdLoginActivity.class);
        intent.putExtra("username", username);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_psd_login);
        username = getIntent().getStringExtra("username");
        initView();
    }


    private void initView() {
        binding.layoutBack.setOnClickListener(this);
        binding.tvChangeLoginType.setOnClickListener(this);
        binding.ivEye.setOnClickListener(this);
        binding.btnLogin.setOnClickListener(this);
        binding.tvForgotPsd.setOnClickListener(this);
        binding.ivInputClearPsd.setOnClickListener(this);
        binding.etPsd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String etNewPsd = charSequence.toString().trim();
                if (etNewPsd.length() == 0) {
                    binding.ivInputClearPsd.setVisibility(View.INVISIBLE);
                } else {
                    binding.ivInputClearPsd.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_back:
                finish();
                break;
            case R.id.tv_change_login_type:
                initPop();
                break;
            case R.id.iv_eye:
                if (psdVisible == 0) {
                    psdVisible = 1;
                    binding.ivEye.setImageResource(R.drawable.open_eye);
                    binding.etPsd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    psdVisible = 0;
                    binding.ivEye.setImageResource(R.drawable.cl_eye);
                    binding.etPsd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                break;
            case R.id.btn_login:
                String etPassword = binding.etPsd.getText().toString().trim();
                if (TextUtils.isEmpty(etPassword)) {
                    ToastUtil.toast("请输入登录密码");
                    return;
                }
                getAuthCode(username, etPassword);
                break;
            case R.id.tv_forgot_psd:
                doAccountIsAlive(username);
                break;
            case R.id.iv_input_clear_psd:
                binding.etPsd.setText("");
                break;


        }
    }


    private void initPop() {
        View popView = LayoutInflater.from(PsdLoginActivity.this).inflate(R.layout.pop_other_login_type_layout, null);
        final PopupWindow popupWindow = new PopupWindow(popView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        popView.findViewById(R.id.tv_psd_login).setVisibility(View.GONE);
        popView.findViewById(R.id.view_line_psd).setVisibility(View.GONE);
        popView.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });
        popView.findViewById(R.id.tv_finger_login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                boolean supportFingerprint = supportFingerprint();
                if (supportFingerprint) {
                    FingerLoginActivity.callMe(PsdLoginActivity.this, username);
                }
            }
        });
        popView.findViewById(R.id.tv_face_login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(PsdLoginActivity.this, com.dff.ytsdkkit.MainActivity.class));
            }
        });
        com.dff.ytsdkkit.MainActivity.setiMainActivity(new com.dff.ytsdkkit.MainActivity.IMainActivity() {
            @Override
            public void result(byte[] image) {
                //人脸识别返回的数据
                Log.i("人脸识别返回的数据",new String(image));
                popupWindow.dismiss();
            }
        });


        //设置SelectPicPopupWindow弹出窗体可点击
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(getResources().getColor(R.color.transparent_background_25));
        // 设置PickPopupWindow弹出窗体的背景
        popupWindow.setBackgroundDrawable(dw);
        popupWindow.setClippingEnabled(false);
        popupWindow.setAnimationStyle(R.style.PopupAnimaFade);
        popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);
    }


    private void getAuthCode(String etAccount, String etPassword) {
        showLoading();
        SharedPreferenceUtils.getInstance().put(PsdLoginActivity.this, Constant.TOKEN, "Basic TlNUQ0FQUDphbXR1V0d0SVFtSlZkMW8wWW04eU1VMTZVVlExZHowOQ==");
        RetrofitUtils.getService().getAuthCode("1", "1").enqueue(new CustomCallBack<ResponseBody>() {
            @Override
            public void onFailure(Call call, Throwable t) {
                super.onFailure(call, t);
                hideLoading();
            }

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (response.body() != null) {
                        String result = response.body().string();
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            JSONObject data = jsonObject.getJSONObject("data");
                            AuthCodeModel authCodeModel = GsonUtils.gsonToBean(data.toString(), AuthCodeModel.class);
                            String encodeStr = XORUtils.entOrDocXOR(etAccount + "@@" + etPassword, authCodeModel.getAuthorizationValue());
                            String base64EncodeToString = XORUtils.base64EncodeToString(encodeStr);
                            base64EncodeToString = base64EncodeToString.replaceAll("[\\s*\t\n\r]", "");
                            String password = base64EncodeToString + "@@" + authCodeModel.getAuthorizationKey();
                            LoginDto loginDto = new LoginDto();
                            loginDto.setGrantType("password");
                            loginDto.setPassword(password);
                            loginDto.setUsername(etAccount);


                            String certDn = CertUtils.getCertDn(PsdLoginActivity.this, etAccount);
                            loginDto.setCertDn(certDn);
                            String PIN = (String) SharedPreferenceUtils.getInstance().get(PsdLoginActivity.this, etAccount, "");
                            if (!TextUtils.isEmpty(PIN)) {
                                CertUtils.sign(PsdLoginActivity.this, 1, etAccount, PIN, etAccount + "+" + certDn, new CertUtils.OnSignCallBackListener() {
                                    @Override
                                    public void onSignCallBack(String sign) {
                                        if (!TextUtils.isEmpty(sign)) {
                                            loginDto.setSign(sign);
                                            doLogin(loginDto, etPassword);
                                        }
                                    }
                                });
                            }else {
                                hideLoading();
                            }
                        } else {
                            hideLoading();
                            String msg = jsonObject.getString("msg");
                            ToastUtil.toast(msg);
                        }
                    } else {
                        hideLoading();
                        ResponseBody errorResponseBody = response.errorBody();
                        if (errorResponseBody != null) {
                            ToastUtil.toast(errorResponseBody.string());
                        }
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                    hideLoading();
                }
            }
        });
    }


    private void doLogin(LoginDto loginDto, String etPassword) {
        RetrofitUtils.getService().doLogin("1", "1", loginDto).enqueue(new CustomCallBack<ResponseBody>() {

            @Override
            public void onFailure(Call call, Throwable t) {
                super.onFailure(call, t);
                hideLoading();
            }

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//                //极光推送用户id设置为别名
//                TagAliasOperatorHelper.TagAliasBean tagAliasBean = new TagAliasOperatorHelper.TagAliasBean();
//                tagAliasBean.action = ACTION_SET;
//                tagAliasBean.alias = loginModel.getUserId();
//                tagAliasBean.isAliasAction = true;
//                TagAliasOperatorHelper.getInstance().handleAction(LoginActivity.this, 0, tagAliasBean);
//                JPushInterface.resumePush(LoginActivity.this);
                hideLoading();
                try {
                    if (response.body() != null) {
                        String result = response.body().string();
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            JSONObject data = jsonObject.getJSONObject("data");
                            LoginModel loginModel = GsonUtils.gsonToBean(data.toString(), LoginModel.class);
                            SharedPreferenceUtils.getInstance().put(PsdLoginActivity.this, Constant.TOKEN, Util.capitalize(loginModel.getTokenType()) + " " + loginModel.getAccessToken());
                            SharedPreferenceUtils.getInstance().put(PsdLoginActivity.this, Constant.CURRENT_LOGIN_ACCOUNT, loginDto.getUsername());
                            try {
                                String bodyStr = XORUtils.jwtDecoded(loginModel.getAccessToken());
                                TokenBodyModel tokenBodyModel = GsonUtils.gsonToBean(bodyStr, TokenBodyModel.class);
                                String userName = tokenBodyModel.getUserName();
                                TokenUserNameModel tokenUserNameModel = GsonUtils.gsonToBean(userName, TokenUserNameModel.class);
                                Integer firstEnter = tokenUserNameModel.getFirstEnter();
                                if (firstEnter == 1 || firstEnter == 2) {
                                    SetNewLoginPsdActivity.callMe(PsdLoginActivity.this, loginDto.getUsername());
                                } else {
                                    SharedPreferenceUtils.getInstance().saveAccount(PsdLoginActivity.this, username);
                                    MainActivity.callMe(PsdLoginActivity.this);
                                    finish();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            String msg = jsonObject.getString("msg");
                            ToastUtil.toast(msg);
                        }
                    } else {
                        ResponseBody errorResponseBody = response.errorBody();
                        if (errorResponseBody != null) {
                            ToastUtil.toast(errorResponseBody.string());
                        }
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    // 是否支持指纹
    public boolean supportFingerprint() {
        if (Build.VERSION.SDK_INT < 23) {
//            ToastUtil.toast("您的系统版本过低，不支持指纹功能");
            return false;
        } else {
            KeyguardManager keyguardManager = getSystemService(KeyguardManager.class);
            FingerprintManager fingerprintManager = getSystemService(FingerprintManager.class);
            if (fingerprintManager != null) {
                if (!fingerprintManager.isHardwareDetected()) {
                    ToastUtil.toast("您的手机不支持指纹功能");
                    return false;
                } else if (keyguardManager != null) {
                    if (!keyguardManager.isKeyguardSecure()) {
                        ToastUtil.toast("您还未设置锁屏，请先设置锁屏并添加一个指纹");
                        return false;
                    } else if (!fingerprintManager.hasEnrolledFingerprints()) {
                        ToastUtil.toast("您至少需要在系统设置中添加一个指纹");
                        return false;
                    }
                } else {
//                    ToastUtil.toast("键盘管理初始化失败");
                    return false;
                }
            } else {
//                ToastUtil.toast("指纹管理初始化失败");
                return false;
            }
        }
        return true;
    }


    private void doAccountIsAlive(String etAccount) {
        showLoading();
        RetrofitUtilsTwo.getService().doAccountIsAlive("1", "1", etAccount).enqueue(new CustomCallBack<ResponseBody>() {

            @Override
            public void onFailure(Call call, Throwable t) {
                super.onFailure(call, t);
                hideLoading();
            }

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                hideLoading();
                try {
                    if (response.body() != null) {
                        String result = response.body().string();
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            JSONObject data = jsonObject.optJSONObject("data");
                            int isMobile = data.optInt("isMobile");
                            if (isMobile == 3) {
                                String mobile = data.optString("mobile");
                                ForgotPsdTwoActivity.callMe(PsdLoginActivity.this, etAccount, mobile);
                            } else {
                                binding.tvError.setText("资金账号未激活，请输入正确的账号");
                                binding.tvError.setVisibility(View.VISIBLE);
                            }
                        } else {
                            String msg = jsonObject.getString("msg");
                            ToastUtil.toast(msg);
                        }
                    } else {
                        ResponseBody errorResponseBody = response.errorBody();
                        if (errorResponseBody != null) {
                            ToastUtil.toast(errorResponseBody.string());
                        }
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


}